/**
 * @description  : 图片上传组件
 * @descriptionDetail : 图片上传组件
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-10-03 17:10:52
 */
<template>
  <view class="upload-content">
    <block v-for="(item, index) in imageList" :key="index">
      <view class="upload-item">
        <image class="upload-img" :src="item.filePath" mode="aspectFill" @click="previewImage(index)"></image>
        <image
          class="upload-del-btn" 
          src="" 
          mode="scaleToFill" 
          v-if="canDel"
          @click="delImage(index)"
        >
        </image>
        <view class="upload-progress" v-if="item.progress < 100">
          {{ item.progress }}%
        </view>
      </view>
    </block>
    <view class="upload-add-btn" v-if="rduLength > 0 && canAdd" @click="chooseImage"></view>
    <u-modal title="提示" :show-cancel-button="true" cancel-text="取消" v-model="showDelete" @confirm="confirmDelete" content="是否放弃此张图片"/>
  </view>
</template>

<script>
import commonService from '@/service/internal/common.service';
import UModal from "../uview-ui/components/u-modal/u-modal";
import reqHelper from "@/common/reqHelper";
import {getForceHeader,} from "@/common/force.js";
export default {
  components: { UModal, },
  props: {
    url: {
      type: String,
      default: commonService.uploadFile, // 上传接口地址
    },
    bizId: {
      type: String,
      value: '', // 上传接口地址
    },
    count: {
      type: Number,
      value: 4, // 单次可选择的图片数量
    },
    length: {
      type: Number,
      value: 50, // 可上传总数量
    },
    // 新增的一些属性
    header:{},
    customDel:{},
    delUrl:{
      type: String,
      default: commonService.deleteFile, // 删除接口
    },
    onSuccess:{
      type: Function,
      value: '', // 删除接口
    },
    renderImages:{
      type: Function,
      default: () => {},
    },
    canDel:{  // 是否可以删除
      type: Boolean,
      default:true,
    },
    // 是否能添加
    canAdd:{
      type: Boolean,
      value: true,
      default:true,
    },
    extForm: {  // 表单额外提交数据
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      imageList: [],
      showDelete:false,
      curImage:0,
    };
  },
  computed: {
    rduLength(){
      return this.length - this.imageList.length;
    },
  },
  created(){
    this.renderImages && this.renderImages(this).then(r => this.imageList = r);
  },
  methods: {
    // 选择图片
    chooseImage: function(){
      uni.chooseImage({
        count: this.rduLength < this.count ? this.rduLength : this.count, // 最多可以选择的图片张数，默认9
        sizeType: ['original', 'compressed',], // original 原图，compressed 压缩图，默认二者都有
        sourceType: ['album','camera',], // album 从相册选图，camera 使用相机，默认二者都有
        success: (res) => {
          const images = res.tempFilePaths;
          this.uploadFiles(images);
        },
      });
    },
    // 上传图片
    async uploadFiles(images){
      uni.showLoading({
        title: '上传中..',
        mask: true,
      });
      try{
        this.uploadImage(images[0]).then(rs => {
          if(this.onSuccess){
            this.imageList = this.onSuccess(this.imageList,rs,this);
            uni.hideLoading();
          } else {
            this.imageList.push({
              filePath: images[0],
              progress: 100,
            });
          }
          images.splice(0, 1);
          // 判断是否需要继续上传
          if(images.length > 0 && this.rduLength > 0){
            this.uploadFiles(images);
          }else{
            uni.hideLoading();
          }
        }, err => {
          // 上传失败处理
          this.imageList.pop();
          uni.hideLoading();
          uni.showToast({
            title: '上传中出现问题，已终止上传',
            icon: 'none',
            mask: true,
            duration: 2000,
          });
        });
      }catch(err){
        console.error(err);
        return;
      }
    },
    uploadImage: function(file){
      return new Promise((resolve, reject) => {
        // 发送给后端的附加参数
        const formData = {
          thumb_mode: 1,
          ...this.extForm,
        };
        let header =  this.header || {};
        if(typeof header === 'function'){
          header = header();
        }
        header = Object.assign(header, getForceHeader('json', this.url, formData, uni.getStorageSync("tk")));
        this.uploadTask = uni.uploadFile({
          url: this.url, 
          filePath: file,
          name: 'file',
          attrCode: this.bizId,
          formData: formData,
          header: Object.assign(header, {tk: uni.getStorageSync("tk"),}),
          success(uploadFileResult){
            console.log("上传结果", uploadFileResult);
            const uploadFileRes = JSON.parse(uploadFileResult.data) || {};
            if((uploadFileResult.statusCode == 200 || (uploadFileRes.status === 1 && uploadFileRes.data)) && uploadFileRes.success){
              resolve(uploadFileRes.data || uploadFileRes.bean);
            }else{
              reject('上传失败');
            }
          }, 
          fail(){
            reject('网络链接错误');
          },
        });
        // 上传进度
        this.uploadTask.onProgressUpdate((progressRes) => {
          this.imageList.length > 0 && (this.imageList[this.imageList.length - 1].progress = progressRes.progress);
        });
      });
    },
    // 删除图片
    delImage(index){
      this.curImage = index;
      uni.showModal({
        title: "提示",
        content: '确定要放弃这张图片么？',
        success: (confirmRes) => {
          if (confirmRes.confirm) {
            this.confirmDelete();
          } 
        },
      });
    },
    // 删除图片
    confirmDelete(){
      let imageInfo = this.imageList[this.curImage];
      if(this.delUrl) {
        uni.showLoading({
          title: '图片删除中..',
          mask: true,
        });
        reqHelper.get({fileUuids: imageInfo.gfiId || imageInfo.fileUuid,fileId: imageInfo.gfiId || imageInfo.fileUuid,},this.delUrl).then(r => {
          this.imageList.splice(this.curImage, 1);
          this.onSuccess && this.onSuccess(this.imageList,null,this);
          uni.hideLoading();
        });
      }

    },
    // 预览图片
    previewImage: function(index){
      const urls = [];
      this.imageList.forEach((item) => {
        urls.push(item.filePath);
      })
      uni.previewImage({
        current: urls[index],
        urls: urls,
        indicator: "number",
      })
    },
  },
}
</script>

<style lang="scss">
	.upload-content{
		padding:24upx 0 0 28upx;
		background-color: #fff;
		overflow:hidden;
	}
	.upload-item{
		position: relative;
		float:left;
		width:150upx;
		height:150upx;
		margin-right:30upx;
		margin-bottom:30upx;
		&:nth-child(4n){
			margin-right:0;
		}
		.upload-img{
			width:100%;
			height:100%;
			border-radius:8upx;
		}
		.upload-del-btn{
			position: absolute;
			right:-16upx;
			top:-14upx;
			width:36upx;
			height:36upx;
			border: 4upx solid #fff;
			border-radius: 100px;
		}
		.upload-progress{
			position: absolute;
			left:0;
			top:0;
			display:flex;
			align-items:center;
			justify-content: center;
			width:100%;
			height:100%;
			background-color: rgba(0,0,0,.4);
			color:#fff;
			font-size:24upx;
			border-radius:8upx;
		}
	}
	.upload-add-btn {
		position: relative;
		float:left;
		width: 150upx;
		height: 150upx;
		z-index: 99;
		border-radius:8upx;
		background:#f9f9f9;
		&:before,
		&:after {
			content: " ";
			position: absolute;
			top: 50%;
			left: 50%;
			-webkit-transform: translate(-50%, -50%);
			transform: translate(-50%, -50%);
			width: 4upx;
			height: 60upx;
			background-color: #d6d6d6;
		}
		&:after {
			width: 60upx;
			height: 4upx;
		}
		&:active {
			background-color: #f7f7f7;
		}
	}


</style>
